package golf.stockinfo.simulationweb.servlet;

import golf.stockinfo.simulationweb.core.SimulationThread;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class StartSimulation
 */
@WebServlet(name="startSimulation", urlPatterns={"/start"}, asyncSupported=true)
public class StartSimulation extends HttpServlet {
       
    /**
	 * 
	 */
	public static final long serialVersionUID = 8674751975541466044L;

	/**
     * @see HttpServlet#HttpServlet()
     */
    public StartSimulation() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		short smavETF = Short.parseShort(request.getParameter("smavETF"));
		short smavTFEX = Short.parseShort(request.getParameter("smavTFEX"));
		
		int threadObjectKey = smavETF * 1000 + smavTFEX;
        
		if(Status.ALL_THREADS.get(threadObjectKey) == null){
			Status.ALL_THREADS.put(threadObjectKey, new SimulationThread(smavETF, smavTFEX));
		}else{
			if(!Status.ALL_THREADS.get(threadObjectKey).isThreadAlive()){
				Status.ALL_THREADS.put(threadObjectKey, new SimulationThread(smavETF, smavTFEX));
			}
		}
		
		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		out.println("Job is running");
		out.close();
	}
	

}
